<template>
  <!-- item.temporaryState==3用于专业组审核 -->
  <div
    v-if="
      (teacherId == item.principalId && item.temporaryState == 0) ||
      item.temporaryState == 1 ||
      item.temporaryState == 3
    "
    class="temp shou"
    @click.prevent="toDetail(item)"
  >
    <div class="rela flex coverBox">
      <img class="cover" :src="item.coursePic" alt="加载失败" />
      <img
        v-if="item.temporaryState == 1"
        :src="require(`@/assets/images/status${item.status}.png`)"
        class="coverTip absolute"
        alt="加载失败"
      />
      <img
        v-if="item.temporaryState == 0 || item.temporaryState == 3"
        :src="require(`@/assets/images/temporary${item.status}.png`)"
        class="coverTip absolute"
        alt="加载失败"
      />
    </div>
    <div class="nameBox flexBet">
      <div class="name overTxt">
        <tooltip position="bottom-start" :text="item.courseName" width="100%" />
      </div>
      <el-popover
        v-if="
          (item.teacherIds ? item.teacherIds : '')
            .split(',')
            .indexOf(teacherId + '') == '-1' && item.temporaryState != 3
        "
        placement="bottom"
        trigger="click"
        ref="popoverName"
      >
        <!-- 页面内容 -->
        <div
          class="flex showContent"
          slot="reference"
          @click.stop="getInfo(item)"
        ></div>
        <!-- 激活内容 -->
        <!-- 2待提交 3待分院审核 4待学校审核 5已驳回 6 待专业组审核 -->
        <div :class="item.status==2||item.status==5?'min-w hideContent':'hideContent'">
          <div
            v-if="
              (item.status != 3 &&
                item.status != 4 &&
                item.status != 6 &&
                item.temporaryState == 0) ||
              (item.temporaryState == 1 && item.status != 0 && item.status != 1)
            "
            class="flex ctemp shou"
            @click="courseEdit(item)"
          >
            <img src="@/assets/images/classify/handle1.png" alt="加载失败" />编辑
          </div>
          <div
            v-if="item.temporaryState == 0"
            class="flex ctemp shou"
            @click="copyDraft(item)"
          >
            <img src="@/assets/images/classify/handle2.png" alt="加载失败" />复制
          </div>
          <template v-if="!showSync">
            <div
              v-if="item.status == 2 || item.status == 5"
              class="flex ctemp shou"
              @click="handleSubmitAudit(item)"
            >
              <img src="@/assets/images/classify/handle9.png" alt="加载失败" />提交审核
            </div>
          </template>
          <template v-if="showSync">
            <div
              v-if="item.status == 2 || item.status == 5"
              class="flex ctemp shou"
              @click="syncSubmitAudit(item)"
            >
              <img
                src="@/assets/images/classify/handle9.png"
                alt="加载失败"
              />同步至正式课
            </div>
          </template>

          <div
            v-if="item.status == 3 || item.status == 4 || item.status == 6"
            class="flex ctemp shou"
            @click="handleCancelAudit(item)"
          >
            <img src="@/assets/images/classify/handle8.png" alt="加载失败" />撤销审核
          </div>
          <div
            v-if="item.status == 1 && item.temporaryState == 1"
            class="flex ctemp shou"
            @click="courseStatus(item, 0)"
          >
            <img src="@/assets/images/classify/handle3.png" alt="加载失败" />启用
          </div>
          <div
            v-if="item.status == 0 && item.temporaryState == 1"
            class="flex ctemp shou"
            @click="courseStatus(item, 1)"
          >
            <img src="@/assets/images/classify/handle5.png" alt="加载失败" />停用
          </div>
          <div
            v-if="item.status == 5"
            class="flex ctemp shou"
            @click="courseReason(item)"
          >
            <img src="@/assets/images/classify/handle7.png" alt="加载失败" />驳回原因
          </div>
          <div
            v-if="
              item.temporaryState == 0 && (item.status == 2 || item.status == 5)
            "
            class="flex ctemp shou"
            @click="handleCancelUpdate(item)"
          >
            <img src="@/assets/images/classify/handle8.png" alt="加载失败" />撤销编辑
          </div>
          <div
            v-if="
              (item.status != 0 && item.temporaryState == 1) ||
              (item.status != 3 &&
                item.status != 4 &&
                item.status != 6 &&
                item.temporaryState == 0)
            "
            class="flex ctemp shou"
            @click="courseDel(item.courseId)"
          >
            <img src="@/assets/images/classify/handle4.png" alt="加载失败" />删除
          </div>
        </div>
      </el-popover>
    </div>
    <div class="infobox flex">
      <div class="wname overTxt">{{ item.workstationNames }}</div>
    </div>
    <reject :open.sync="rejectOpen" :item="rejectItem" :type="3"></reject>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="showDia = false"
      :visible="showDia"
      width="500px"
      append-to-body
    >
      <div slot="title">提交/同步失败</div>
      <div class="delete_content">
        <div>
          课程中有考核异常（大题题目数量为空/题库题目数量少于已配置数量），请重新编辑！
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDia = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { disciplineGroup_onOffStatus } from "@/api/disciplineGroup/disciplineGroup";
import {
  getDistributionList,
  delCourse,
  editCourse,
  editCourseStatus,
  checkScorePercent,
  revokeCourse,
  copyCourse,
  editCourseCount,
  getExceptionExam,
} from "@/api/course/course";
import addStudent from "@/views/tea_course/components/addStudent.vue";
import reject from "@/components/reject.vue";
import { getInfo } from "@/api/login";

export default {
  components: { reject, addStudent },
  props: {
    item: Object,
    type: String,
  },
  data() {
    return {
      teacherId: this.$store.getters.teacherId,
      rejectOpen: false,
      showDia: false,
      rejectItem: {},
      courseId: 0,
      showSync: false,
    };
  },
  methods: {
    async editCourseCount(courseId) {
      let res = await editCourseCount(courseId);
    },
    async getInfo(item) {
      if (item.status == 2) {
        let res = await getInfo();
        const { code, school } = res;
        if (code == 200) {
          if (
            school.courseNeedCheckBranch == 0 &&
            school.courseNeedCheckSchool == 0 &&
            school.courseNeedCheckDiscipline == 0
          ) {
            this.showSync = true;
          } else {
            this.showSync = false;
          }
        }
      }
    },
    /* 撤销编辑 */
    handleCancelUpdate(row) {
      this.$confirm(
        `确定撤销【${row.courseName}】的编辑内容吗?撤销后将恢复至上次通过审核时的版本(同本课程当前正式版)!`,
        "撤销编辑确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          revokeCourse(row.courseId).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.$emit("refresh", true);
            this.$refs["popoverName"].doClose();
          });
        })
        .catch(() => {});
    },
    async checkScorePercent(courseId) {
      let res = await checkScorePercent(courseId);
      if (res.code == 200) {
        return res.data;
      } else {
        return "false";
      }
    },
    //获取课程下有哪些目录存在异常考核
    async getExceptionExam(row) {
      try {
        let res = await getExceptionExam(row.courseId);
        const { code, data } = res;
        if (code == 200) {
          return data ? data.length : 0;
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 获取当前课程是否在导入
    getImportCourse(row) {
      this.$store.dispatch('startPolling');
      return this.$store.getters.courseIds.includes(row.courseId);
    },
    /* 提交审核 */
    async handleSubmitAudit(row) {
      if(this.getImportCourse(row)){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      console.log(row.disciplineGroupId);
      let open = await disciplineGroup_onOffStatus();
      if (!row.disciplineGroupId && open.data.onOffStatus !== 0) {
        this.$confirm("请先完善【课程简介】并保存！", "提交失败", {
          showCancelButton: false,
          confirmButtonText: "关闭",
          type: "warning",
        }).then(() => {});
        return;
      }
      console.log(row);
      //存在异常考核
      let num = await this.getExceptionExam(row);
      if (num) {
        this.showDia = true;
        return;
      }
      let state = await this.checkScorePercent(row.courseId);
      if (state == "false") {
        return;
      }
      if (state.type == 3) {
        let str = "";
        for (const datum of state.data) {
          str += `【${datum.ancestorsName}】`;
        }
        this.$modal.msgWarning(
          `${str}考核：及格分高于总分,请前往该考核的【考核配置信息】中修改`
        );
        return;
      }
      let txt;
      if (state.data != "100" || state.type == 2) {
        this.$confirm(
          "课程未配分，请在课程内容中，点击左上角【课程配分】按钮并完善配分。",
          "提交失败",
          {
            showCancelButton: false,
            confirmButtonText: "关闭",
            type: "warning",
          }
        ).then(() => {});
        return;
      } else {
        try {
          // 检测总的后 检测明细
          let examRes = await getDistributionList(row.courseId);
          console.log("examRes", examRes);
          if (examRes.code == 200) {
            let can = true;
            let homeworkScore = 0;
            let processScore = 0;
            let examScore = 0;
            let  homeworkScorePercentage=examRes.data.homeworkScorePercentage;
            let processScorePercentage=examRes.data.processScorePercentage;
            let examScorePercentage=0;
            if (examRes.data.homeworkCourseIndexScoreEntityList.length > 0) {
              homeworkScore =
                examRes.data.homeworkCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.homeworkScorePercentage;
                  },
                  0
                );
            }
            if (examRes.data.processCourseIndexScoreEntityList.length > 0) {
              processScore =
                examRes.data.processCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.processScorePercentage;
                  },
                  0
                );
            }
            if (row.courseTemplate == 1) {
              if (examRes.data.ccCourseIndexScoreEntityList.length > 0) {
                examScore = examRes.data.ccCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.scorePercentage;
                  },
                  0
                );
              }
              examScorePercentage=examRes.data.examScorePercentage;
            }
            if (row.courseTemplate == 1) {
              can =
                (homeworkScore == 100||homeworkScorePercentage==0) && (processScore == 100||processScorePercentage==0) && (examScore == 100||examScorePercentage==0)
                  ? true
                  : false;
            } else {
              can = (homeworkScore == 100||homeworkScorePercentage==0) && (processScore == 100||processScorePercentage==0) ? true : false;
            }
            console.log("can", homeworkScore, processScore, examScore, can);
            if (!can) {
              if (row.courseTemplate != 0) {
                console.log(homeworkScore,homeworkScorePercentage,homeworkScore!=100&&homeworkScorePercentage!=0)
                txt = `${(homeworkScore!=100&&homeworkScorePercentage!=0)?'课后作业  ':''}${(processScore!=100&&processScorePercentage!=0)?'任务考核  ':''}${(examScore!=100&&examScorePercentage!=0)?'终结性考核  ':''}配分不足100%，且提交后课程将进入审核流程，审核结束前不可继续编辑，是否确认提交?`;
              } else {
                txt = `${(homeworkScore!=100&&homeworkScorePercentage!=0)?'课后作业  ':''}${(processScore!=100&&processScorePercentage!=0)?'课后考核  ':''}配分不足100%，且提交后课程将进入审核流程，审核结束前不可继续编辑，是否确认提交?`;
              }
            } else {
              txt = "提交后课程将进入审核流程，审核结束前不可继续编辑，是否确认提交?";
            }
          }
        } finally {
        }
      }
      this.$confirm(txt, "提交确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "正在提交审核",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.3)",
          });
          let params = {
            courseId: row.courseId,
            type: 2,
          };
          editCourseStatus(params.type, params.courseId)
            .then((response) => {
              //判断是否需要审核不需要审核直接提示审核通过  school.courseNeedCheckBranch==1&&school.courseNeedCheckSchool==1
              this.$modal.msgSuccess("提交审核成功");
              loading.close();
              this.$emit("refresh", true);
              this.$EventBus.$emit("courseStatusRefresh", true);
              this.$refs["popoverName"].doClose();
            })
            .catch((error) => {
              loading.close();
            });
        })
        .catch(() => {});
    },
    /* 同步至正式课 */
    async syncSubmitAudit(row) {
      if(this.getImportCourse(row)){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      console.log(row.disciplineGroupId);
      let open = await disciplineGroup_onOffStatus();
      if (!row.disciplineGroupId && open.data.onOffStatus !== 0) {
        this.$confirm("请先完善【课程简介】并保存！", "同步失败", {
          showCancelButton: false,
          confirmButtonText: "关闭",
          type: "warning",
        }).then(() => {});
        return;
      }
      //存在异常考核
      let num = await this.getExceptionExam(row);
      if (num) {
        this.showDia = true;
        return;
      }
      let state = await this.checkScorePercent(row.courseId);
      if (state == "false") {
        return;
      }

      if (state.type == 3) {
        let str = "";
        for (const datum of state.data) {
          str += `【${datum.ancestorsName}】`;
        }
        this.$modal.msgWarning(
          `${str}考核：及格分高于总分,请前往该考核的【考核配置信息】中修改`
        );
        return;
      }
      let txt;
      if (state.data != "100" || state.type == 2) {
        this.$confirm(
          "课程未配分，请在课程内容中，点击左上角【课程配分】按钮并完善配分。",
          "同步失败",
          {
            showCancelButton: false,
            confirmButtonText: "关闭",
            type: "warning",
          }
        ).then(() => {});
        return;
      } else {
        try {
          // 检测总的后 检测明细
          let examRes = await getDistributionList(row.courseId);
          if (examRes.code == 200) {
            let can = true;
            let homeworkScore = 0;
            let processScore = 0;
            let examScore = 0;
            let  homeworkScorePercentage=examRes.data.homeworkScorePercentage;
            let processScorePercentage=examRes.data.processScorePercentage;
            let examScorePercentage=0;
            if (examRes.data.homeworkCourseIndexScoreEntityList.length > 0) {
              homeworkScore =
                examRes.data.homeworkCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.homeworkScorePercentage;
                  },
                  0
                );

            }
            if (examRes.data.processCourseIndexScoreEntityList.length > 0) {
              processScore =
                examRes.data.processCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.processScorePercentage;
                  },
                  0
                );
            }
            if (row.courseTemplate == 1) {
              if (examRes.data.ccCourseIndexScoreEntityList.length > 0) {
                examScore = examRes.data.ccCourseIndexScoreEntityList.reduce(
                  (accumulator, currentValue) => {
                    return accumulator + currentValue.scorePercentage;
                  },
                  0
                );
              }
              examScorePercentage=examRes.data.examScorePercentage;
            }
            if (row.courseTemplate == 1) {
              can =
                (homeworkScore == 100||homeworkScorePercentage==0) && (processScore == 100||processScorePercentage==0) && (examScore == 100||examScorePercentage==0)
                  ? true
                  : false;
            } else {
              can = (homeworkScore == 100||homeworkScorePercentage==0) && (processScore == 100||processScorePercentage==0) ? true : false;
            }
            console.log("can", homeworkScore, processScore, examScore, can);
            if (!can) {
              if (row.courseTemplate != 0) {
                console.log(homeworkScore,homeworkScorePercentage,homeworkScore!=100&&homeworkScorePercentage!=0)
                txt = `${(homeworkScore!=100&&homeworkScorePercentage!=0)?'课后作业  ':''}${(processScore!=100&&processScorePercentage!=0)?'任务考核  ':''}${(examScore!=100&&examScorePercentage!=0)?'终结性考核  ':''}配分不足100%，是否确认同步至正式课?`;
              } else {
                txt = `${(homeworkScore!=100&&homeworkScorePercentage!=0)?'课后作业  ':''}${(processScore!=100&&processScorePercentage!=0)?'课后考核  ':''}配分不足100%，是否确认同步至正式课?`;
              }
            } else {
              txt = "同步后，草稿课程将更新至正式课程，是否确认操作？";
            }
          }
        } finally {
        }
      }
      this.$confirm(txt, "同步确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "正在同步",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.3)",
          });
          let params = {
            courseId: row.courseId,
            type: 2,
          };
          editCourseStatus(params.type, params.courseId)
            .then((response) => {
              this.$modal.msgSuccess("同步成功");
              loading.close();
              this.$emit("refresh", true);
              this.$refs["popoverName"].doClose();
            })
            .catch((error) => {
              loading.close();
            });
        })
        .catch(() => {});
    },
    /* 撤销审核 */
    handleCancelAudit(row) {
      if(this.getImportCourse(row)){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      this.$confirm(
        `确定撤销【${row.courseName}】的审核申请吗？撤销后如需审核，需重新提交审核申请！`,
        "撤销审核确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            courseId: row.courseId,
            type: 3,
          };
          let res;
          try {
            res = await editCourseStatus(params.type, params.courseId);
            if (res.code == 200) {
              this.$modal.msgSuccess("撤销审核成功");
              this.$emit("refresh", true);
              this.$refs["popoverName"].doClose();
            }
          } catch (e) {
            if (e.message == `撤销失败，【${row.courseName}】已审核`) {
              this.$emit("refresh", true);
              this.$refs["popoverName"].doClose();
            }
          }
        })
        .catch(() => {});
    },
    /* 复制 */
    async copyDraft(item) {
      if(this.getImportCourse(item)){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      const loading = this.$loading({
        lock: true,
        text: "正在复制…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.3)",
      });
      let res = await copyCourse(item.courseId);
      if (res.code == 200) {
        this.$modal.msgSuccess("复制成功");
        this.$emit("refresh", true);
        this.$refs["popoverName"].doClose();
        loading.close();
      } else {
        this.$refs["popoverName"].doClose();
        loading.close();
      }
    },
    /* 编辑课程 */
    courseEdit(item) {
      this.editCourseCount(item.courseId);
      if (item.status == 0 && item.temporaryState == 0) {
        this.$confirm(
          `修改时会自动生成一份草稿，修改结束，重新提交审核通过后，会覆盖在用的课程;修改过程中不会影响已经在用的课程`,
          "课程修改提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            let data = JSON.parse(JSON.stringify(item));
            data.status = 2;
            editCourse(data).then((res) => {
              this.$router.push({
                path: "/course/add",
                query: {
                  type: "edit",
                  courseId: item.courseId,
                  modelType: item.courseTemplate,
                },
              });
            });
          })
          .catch(() => {});
      } else {
        this.$router.push({
          path: "/course/add",
          query: {
            type: "edit",
            courseId: item.courseId,
            modelType: item.courseTemplate,
          },
        });
      }
    },
    /* 启用 停用课程 */
    courseStatus(item, status) {
      if(this.getImportCourse(item)){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      this.$confirm(
        `是否确认${status == 0 ? "启用" : "停用"}该课程?${
          status == 0 ? "" : "停用后该课程将无法使用"
        }`,
        "停用确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            courseId: item.courseId,
            type: status,
          };
          let res = await editCourseStatus(params.type, params.courseId);
          if (res.code == 200) {
            this.$modal.msgSuccess(`${status == 0 ? "启用" : "停用"}成功`);
            this.$emit("refresh", true);
            this.$refs["popoverName"].doClose();
          }
        })
        .catch(() => {});
    },
    /* 复制 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
      this.$refs["popoverName"].doClose();
    },
    /* 驳回原因 */
    courseReason(item) {
      this.rejectOpen = true;
      item.uncheckReason = item.rejectReason;
      this.rejectItem = item;
      this.$refs["popoverName"].doClose();
    },
    /* 删除课程 */
    courseDel(courseId) {
      if(this.getImportCourse({courseId:courseId})){
        this.$message("当前课程正在导入中，请稍后再试！")
        return
      }
      this.$confirm(
        "删除课程后，课程将无法编辑，此操作不可撤销，是否确认删除该课程？",
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let res = await delCourse(courseId);
          const { code } = res;
          if (code == 200) {
            this.$modal.msgSuccess("删除成功!");
            this.$emit("refresh", true);
            this.$refs["popoverName"].doClose();
          }
        })
        .catch(() => {});
    },
    // 跳转
    toDetail(item) {
      if (item.temporaryState == 3) {
        this.$router.push({
          path: "/course/add",
          query: {
            type: "audit",
            courseId: item.courseId,
            modelType: item.courseTemplate,
            status: "50",
          },
        });
      } else {
        this.$router.push({
          path: "/course/add",
          query: {
            type: "detail",
            courseId: item.courseId,
            modelType: item.courseTemplate,
          },
        });
      }
    },
  },
  created() {},
  mounted() {},
};
</script>
<style scoped lang='scss'>
.showContent {
  margin-left: 2px;
  width: 26px;
  height: 16px;
  background-size: 26px 16px;
  background-image: url("../assets/images/more1.png");
  background-repeat: no-repeat;
}

.showContent:hover {
  background-image: url("../assets/images/more2.png");
}
.hideContent.min-w{
  min-width: 168px;
}
.hideContent {
  min-width: 138px;
  img {
    margin: auto 17px auto 20px;
    width: 15px;
    height: 15px;
  }

  .ctemp {
    padding-right: 32px;
    box-sizing: border-box;
    font-size: 14px;
    color: #666666;
    line-height: 36px;
    height: 36px;
    border-bottom: 1px solid #edeff0;
  }

  .ctemp:hover {
    background: #f5f5f5;
  }
}

.temp:hover {
  box-shadow: 0 0 20px 0 rgba(0, 55, 50, 0.12);
}

.temp {
  margin: 0 32px 42px 0;
  width: 240px;
  height: 217px;
  background: #ffffff;
  border-radius: 16px;
  border: 1px solid #ebebeb;

  .coverBox {
    margin: 12px 0 0 12px;
    width: 216px;
    height: 135px;
  }

  .cover {
    width: 216px;
    height: 135px;
    background: #f7f7f8;
    border-radius: 8px;
  }

  .coverTip {
    z-index: 3;
    top: 4px;
    left: -20px;
    width: 56px;
    height: 29px;
  }

  .nameBox {
    margin: 8px 0 0 12px;
    width: 210px;
    font-size: 16px;
    color: #333333;
    line-height: 22px;

    .name {
      width: 180px;
    }
  }

  .infobox {
    margin-top: 8px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #999999;
    line-height: 20px;

    .credit {
      margin-left: 12px;
    }

    .wname {
      width: 220px;
      margin-left: 10px;
    }
  }
}
</style>
